package cn.stylefeng.guns.modular.order.controller;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPrivatecar;
import cn.stylefeng.guns.modular.basic.model.params.BasicAddressParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicCarrierParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPrivatecarParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicAddressResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicCarrierResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.order.entity.OrderClientVolDetail;
import cn.stylefeng.guns.modular.order.entity.OrderClientVolSum;
import cn.stylefeng.guns.modular.order.entity.OrderOutcountXlb;
import cn.stylefeng.guns.modular.order.model.params.OrderClientVolDetailParam;
import cn.stylefeng.guns.modular.order.model.params.OrderClientVolSumParam;
import cn.stylefeng.guns.modular.order.model.params.OrderOutcountXlbParam;
import cn.stylefeng.guns.modular.order.model.params.OrderOutpreparePlatooncarParam;
import cn.stylefeng.guns.modular.order.model.result.OrderClientVolSumResult;
import cn.stylefeng.guns.modular.order.service.OrderClientVolDetailService;
import cn.stylefeng.guns.modular.order.service.OrderClientVolSumService;
import cn.stylefeng.guns.modular.order.service.OrderOutcountXlbService;
import cn.stylefeng.guns.modular.order.service.OrderOutpreparePlatooncarService;
import cn.stylefeng.guns.sys.modular.system.entity.Role;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.RoleService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;


/**
 * 新零帮出库汇总控制器
 * @author zhucx
 * @Date 2023-09-30 13:49:55
 */
@Slf4j
@Controller
@RequestMapping("/orderOutcountXlb")
public class OrderOutcountXlbController extends BaseController {

    private String PREFIX = "/order/orderOutcountXlb";

    @Autowired
    private OrderOutcountXlbService orderOutcountXlbService;

    @Autowired
    private UserService userService;

	@Autowired
	private RoleService roleService;

    @Autowired
    private BasicCustomerService basicCustomerService;

	@Autowired
	private BasicAddressService basicAddressService;

    @Autowired
    private BasicCarrierService basicCarrierService;
    
    @Autowired
    private BasicPrivatecarService basicPrivatecarService;

    @Autowired
    private OrderOutpreparePlatooncarService orderOutpreparePlatooncarService;

	@Autowired
	private OrderClientVolSumService orderClientVolSumService;

	@Autowired
	private OrderClientVolDetailService orderClientVolDetailService;
    /**
     * to选择车辆
     */
    @RequestMapping("/toCar")
    public String toCar(Model model) {
    	User user = userService.getcurrentUser();
    	BasicCarrierParam basicCarrierParam = new BasicCarrierParam();
    	basicCarrierParam.setDeliverId(user.getDeliverId());
    	model.addAttribute("carrierlist", basicCarrierService.findListBySpec(basicCarrierParam, user.getOperateId()));
        return PREFIX + "/choiceCar.html";
    }

    /**
     * 查询车辆
     */
    @ResponseBody
    @RequestMapping("/privatecarlist")
    public LayuiPageInfo privatecarlist(BasicPrivatecarParam basicPrivatecarParam,String condition) {
    	User user = userService.getcurrentUser();
    	basicPrivatecarParam.setDeliverId(user.getDeliverId());

		if (condition == null || condition.isEmpty()){
			String roleId = user.getRoleId();
			if(ToolUtil.isNotEmpty(roleId)){
				for(String rId : roleId.split(",")){
					Role byId = roleService.getById(rId);
					if(byId != null && byId.getName().contains("承运商")){
						BasicCarrierParam param = new BasicCarrierParam();
						param.setUserId(user.getUserId());
						BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
						if(bySpec != null){
							basicPrivatecarParam.setPrivatecarFleetId(bySpec.getId());
						}else{
							basicPrivatecarParam.setPrivatecarFleetName(user.getName());
						}
					}
				}
			}
		}

        return this.basicPrivatecarService.findPlatooncarPageBySpec(basicPrivatecarParam,condition,user.getOperateId());
    }

    /**
     * 预排车
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/batchassign")
    @ResponseBody
    public ResponseData batchassign(Long carId, String[] cids) {
    	User user = userService.getcurrentUser();
    	BasicPrivatecar cr = basicPrivatecarService.getById(carId); // 查询自有车信息
		List<OrderOutpreparePlatooncarParam> orderOutpreparePlatooncarParamLs = new ArrayList<>();

		//判断是否已分配
		OrderOutpreparePlatooncarParam orderOutpreparePlatooncarParam  = null;
		for (int i = 0; i < cids.length; i++) {
			orderOutpreparePlatooncarParam  = new OrderOutpreparePlatooncarParam();
			orderOutpreparePlatooncarParam.setCarrierId(Long.parseLong(cr.getPrivatecarFleetId().toString())); // 承运商id
			orderOutpreparePlatooncarParam.setCarrierName(cr.getPrivatecarFleetName()); // 承运商名称
			orderOutpreparePlatooncarParam.setCarnumber(cr.getPrivatecarCarnumber()); // 车牌号
			orderOutpreparePlatooncarParam.setCarId(carId); // 自有车id
			orderOutpreparePlatooncarParam.setSiji(cr.getDriver1()); // 驾驶员1
			orderOutpreparePlatooncarParam.setSijidianhua(cr.getTel1()); // 联系电话1
			orderOutpreparePlatooncarParam.setCreateBy(user.getName());
			orderOutpreparePlatooncarParam.setDeptId(user.getDeptId());
			orderOutpreparePlatooncarParam.setDeliverId(user.getDeliverId());
			OrderClientVolSum orderClientVolSum = orderClientVolSumService.getById(Long.valueOf(cids[i])); // 查询等待派车
			if(orderClientVolSum != null){
                OrderClientVolSumParam orderClientVolSumParam = new OrderClientVolSumParam();
                orderClientVolSumParam.setId(orderClientVolSum.getId());
                orderClientVolSumParam.setUndisVolume(new BigDecimal(0)); // 未排体积设置为 0
                orderClientVolSumService.update(orderClientVolSumParam);

				orderOutpreparePlatooncarParam.setClientVolSumId(orderClientVolSum.getId()); // 等待派车id
				orderOutpreparePlatooncarParam.setClientName(orderClientVolSum.getClientName()); // 客户名称
				orderOutpreparePlatooncarParam.setClientId(orderClientVolSum.getClientId()); // 客户id
				orderOutpreparePlatooncarParam.setV1(orderClientVolSum.getDataDt()); // 数据日期
				orderOutpreparePlatooncarParam.setEstDeliveryDate(new Date()); // 预计配送日期
				orderOutpreparePlatooncarParamLs.add(orderOutpreparePlatooncarParam);
			}
		}

		//保存
		for(OrderOutpreparePlatooncarParam p : orderOutpreparePlatooncarParamLs){
			orderOutpreparePlatooncarService.add(p);
		}

        return ResponseData.success();
    }

    /**
     * 跳转到主页面
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	BasicCarrierParam basicCarrierParam = new BasicCarrierParam();
    	basicCarrierParam.setDeliverId(user.getDeliverId());
    	model.addAttribute("carrierlist", basicCarrierService.findListBySpec(basicCarrierParam,user.getOperateId()));
        return PREFIX + "/orderOutcountXlb.html";
    }

    /**
     * 拉取出库申请单页面
     *
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/topullxlboutorder")
    public String topullxlboutorder(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/pullxlboutorder.html";
    }

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    /**
     * 拉取出库申请单
     *
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/pullxlboutorder")
    @ResponseBody
    public ResponseData pullxlboutorder(String modified_begin,String modified_end, Integer customerId) {
//        String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.outApplicationOrder.find";
		String ModifiedDate = modified_end.substring(0,10);
        String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.outApplicationOrder.find";
        List<String> create_time = new ArrayList<String>();
        create_time.add(modified_begin);
        create_time.add(modified_end);
        BasicCustomer c = basicCustomerService.getById(customerId);
        if(ToolUtil.isEmpty(c.getStoreIdXlb())) {
    		return ResponseData.error("请维护新零帮发货门店id");
        }
        if(ToolUtil.isEmpty(c.getGsnumber())) {
    		return ResponseData.error("请维护新零帮公司号");
        }
    	
		BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
		oauth2tokenParam.setDeliverId(c.getDeliverId());
		oauth2tokenParam.setGsnumber(c.getGsnumber());
		BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
		if(oauth2tokenResult != null) {
			if(ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
				JSONObject json = new JSONObject();
				json.put("store_id", c.getStoreIdXlb());
				json.put("create_time", create_time);
				String post = HttpRequest.post(url)
							.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
		    	JSONObject jsonObject = new JSONObject(post);
				if(jsonObject.get("code").toString().equals("0")) {
			    	List<OrderOutcountXlbParam> add = new ArrayList<OrderOutcountXlbParam>();
					JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
					for (Object object : jsonArray) {
						JSONObject jsonObject2 = new JSONObject(object.toString());
						OrderOutcountXlbParam addpParam = new OrderOutcountXlbParam();
						String client_id = jsonObject2.get("client_id").toString();
						if (ToolUtil.isNotEmpty(client_id)) {//收货客户id
							addpParam.setClientId(client_id);
						}

						String client_name = jsonObject2.get("client_name").toString();
						if (ToolUtil.isNotEmpty(client_name)) {//客户名称
							addpParam.setClientName(client_name);
						}

						String client_type = jsonObject2.get("client_type").toString();
						if (ToolUtil.isNotEmpty(client_type)&&!client_type.equals("null")){//收货客户类型
							addpParam.setClientType(client_type);
						}

						String fid = jsonObject2.get("fid").toString();
						if (ToolUtil.isNotEmpty(fid)) {//单据号
//							OrderOutcountXlbParam ch = new OrderOutcountXlbParam();
//							ch.setFid(fid);
//							OrderOutcountXlbResult chr =  orderOutcountXlbService.checkyouwu(ch);
//							if(chr != null) {
//								continue;
//							}
							addpParam.setFid(fid);
						}

						String item_count = jsonObject2.get("item_count").toString();
						if (ToolUtil.isNotEmpty(item_count)) {//商品数
							addpParam.setItemCount(item_count);
						}

//						String memo = jsonObject2.get("memo").toString();
//						if (ToolUtil.isNotEmpty(memo)) {//备注
//							addpParam.setMemo(memo);
//						}

						String open_stock_quantity = jsonObject2.get("open_stock_quantity").toString();
						if (ToolUtil.isNotEmpty(open_stock_quantity)) {//拆零数量
							addpParam.setOpenStockQuantity(open_stock_quantity);
						}

						String open_stock_sku_kind_num = jsonObject2.get("open_stock_quantity").toString();
						if (ToolUtil.isNotEmpty(open_stock_sku_kind_num)) {//拆零数量
							addpParam.setOpenStockSkuKindNum(open_stock_sku_kind_num);
						}

						String order_fid = jsonObject2.get("order_fid").toString();
						if (ToolUtil.isNotEmpty(order_fid)&&!order_fid.equals("null")) {//关联单据号
							addpParam.setOrderFid(order_fid);
						}

						String order_type = jsonObject2.get("order_type").toString();
						if (ToolUtil.isNotEmpty(order_type)) {//单据类型
							addpParam.setOrderType(order_type);
						}

						String quantity = jsonObject2.get("quantity").toString();
						if (ToolUtil.isNotEmpty(quantity)) {//申请数量
							addpParam.setQuantity(quantity);
						}

						String state = jsonObject2.get("state").toString();
						if (ToolUtil.isNotEmpty(state)) {//状态
							addpParam.setState(state);
						}

						String store_id = jsonObject2.get("store_id").toString();
						if (ToolUtil.isNotEmpty(store_id)) {//发货门店id
							addpParam.setStoreId(store_id);
						}

						String store_name = jsonObject2.get("store_name").toString();
						if (ToolUtil.isNotEmpty(store_name)&&!store_name.equals("null")) {//发货门店名称
							addpParam.setStoreName(store_name);
						} else {
							if(c.getStoreIdXlb().equals("6666600000629")) {
								addpParam.setStoreName("山东德州仓");
							}
							if(c.getStoreIdXlb().equals("6866800000001")) {
								addpParam.setStoreName("辽宁沈阳仓");
							}
							if(c.getStoreIdXlb().equals("6666600000628")) {
								addpParam.setStoreName("山东潍坊仓");
							}
							if(c.getStoreIdXlb().equals("6666600000312")) {
								addpParam.setStoreName("安徽亳州仓");
							}
							if(c.getStoreIdXlb().equals("6666600001990")) {
								addpParam.setStoreName("天津仓");
							}
						}

						String storehouse_id = jsonObject2.get("storehouse_id").toString();
						if (ToolUtil.isNotEmpty(storehouse_id)) {//发货仓库id
							addpParam.setStorehouseId(storehouse_id);
						}

						String storehouse_name = jsonObject2.get("storehouse_name").toString();
						if (ToolUtil.isNotEmpty(storehouse_name)&&!storehouse_name.equals("null")) {//发货仓库名称
							addpParam.setStorehouseName(storehouse_name);
						} else {
							if(c.getStoreIdXlb().equals("6666600000629")) {
								addpParam.setStorehouseName("山东德州仓仓库");
							}
							if(c.getStoreIdXlb().equals("6866800000001")) {
								addpParam.setStorehouseName("辽宁沈阳仓仓库");
							}
							if(c.getStoreIdXlb().equals("6666600000628")) {
								addpParam.setStorehouseName("山东潍坊仓仓库");
							}
							if(c.getStoreIdXlb().equals("6666600000312")) {
								addpParam.setStorehouseName("安徽亳州仓仓库");
							}
							if(c.getStoreIdXlb().equals("6666600001990")) {
								addpParam.setStorehouseName("天津仓仓库");
							}
						}

						String volume = jsonObject2.get("volume").toString();
						if (ToolUtil.isNotEmpty(volume)) {//体积
							addpParam.setVolume(volume);
						}

						String whole_quantity = jsonObject2.get("whole_quantity").toString();
						if (ToolUtil.isNotEmpty(whole_quantity)) {//整件数量
							addpParam.setWholeQuantity(whole_quantity);
						}

						String whole_sku_kind_num = jsonObject2.get("whole_sku_kind_num").toString();
						if (ToolUtil.isNotEmpty(whole_sku_kind_num)&&!whole_sku_kind_num.equals("null")) {//整件sku数
							addpParam.setWholeSkuKindNum(whole_sku_kind_num);
						}

//						String system_memo = jsonObject2.get("system_memo").toString();
//						if (ToolUtil.isNotEmpty(system_memo)&&!system_memo.equals("null")) {//系统备注
//							if(system_memo.indexOf("拆分生成") != -1) {
//								OrderOutcountXlbParam ch = new OrderOutcountXlbParam();
//								ch.setSystemMemo(system_memo);
//								OrderOutcountXlbResult chr =  orderOutcountXlbService.checkyouwu(ch);
//								if(chr != null) {
//									continue;
//								}
//							}
//							if(system_memo.indexOf("合并生成") != -1) {
//								OrderOutcountXlbParam ch = new OrderOutcountXlbParam();
//								ch.setSystemMemo(system_memo);
//								OrderOutcountXlbResult chr =  orderOutcountXlbService.checkyouwu(ch);
//								if(chr != null) {
//									continue;
//								}
//							}
//							addpParam.setSystemMemo(system_memo);
//						}
						addpParam.setCreateTime(new Date());
						addpParam.setDeptId(c.getDeptId());
						addpParam.setDeliverId(c.getDeliverId());
						addpParam.setV1(ModifiedDate);
						add.add(addpParam);
					}
					if(add.size()>0) {
						OrderOutcountXlbParam de = new OrderOutcountXlbParam();
						de.setStoreId(c.getStoreIdXlb());
						de.setV1(ModifiedDate);
						orderOutcountXlbService.deleteBySpec(de);
						orderOutcountXlbService.saveBatchList(add);
					}
				}
			}
		}
        return ResponseData.success();
    }

	/**
	 * 拉取出库申请单
	 *
	 * @author zhucx
	 * @Date 2023-09-30
	 */
	@RequestMapping("/pullxlboutorderNew")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class,timeout = 600)
	public ResponseData pullxlboutorderNew(String modified_begin,String modified_end, Integer customerId) {
		String ModifiedDate = modified_end.substring(0,10);
		User user = userService.getcurrentUser();
		String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.outApplicationOrder.find";
		List<String> create_time = new ArrayList<String>();
		create_time.add(modified_begin);
		create_time.add(modified_end);
		BasicCustomer c = basicCustomerService.getById(customerId);
		if(ToolUtil.isEmpty(c.getStoreIdXlb())) {
			return ResponseData.error("请维护新零帮发货门店id");
		}
		if(ToolUtil.isEmpty(c.getGsnumber())) {
			return ResponseData.error("请维护新零帮公司号");
		}

		BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
		oauth2tokenParam.setDeliverId(c.getDeliverId());
		oauth2tokenParam.setGsnumber(c.getGsnumber());
		BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
		if(oauth2tokenResult != null) {
			if(ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
				JSONObject json = new JSONObject();
				json.put("store_id", c.getStoreIdXlb());
				json.put("create_time", create_time);
//				json.put("state", "INIT");
				String post = HttpRequest.post(url)
						.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//				log.info("================json：{}",json);
				JSONObject jsonObject = new JSONObject(post);
				if(jsonObject.get("code").toString().equals("0")) {
					List<OrderClientVolDetail> add = new ArrayList<OrderClientVolDetail>();
					OrderClientVolDetail addParam = null;
					JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
					for (Object object : jsonArray) {
						JSONObject jsonObject2 = new JSONObject(object.toString());
						addParam = new OrderClientVolDetail();
						String client_id = jsonObject2.get("client_id").toString();
						if (ToolUtil.isNotEmpty(client_id)) {//收货客户id
							addParam.setClientId(client_id);
						}

						String client_name = jsonObject2.get("client_name").toString();
						if (ToolUtil.isNotEmpty(client_name)) {//客户名称
							addParam.setClientName(client_name);
						}

						String fid = jsonObject2.get("fid").toString();
						if (ToolUtil.isNotEmpty(fid)) {//单据号
							addParam.setFid(fid);
						}

						String item_count = jsonObject2.get("item_count").toString();
						if (ToolUtil.isNotEmpty(item_count)) {//商品数
							addParam.setItemCount(Long.valueOf(item_count));
						}

//						String open_stock_quantity = jsonObject2.get("open_stock_quantity").toString();
//						if (ToolUtil.isNotEmpty(open_stock_quantity)) {//拆零数量
//							addParam.setOpenStockQuantity(Long.valueOf(open_stock_quantity));
//						}

//						String open_stock_sku_kind_num = jsonObject2.get("open_stock_quantity").toString();
//						if (ToolUtil.isNotEmpty(open_stock_sku_kind_num)) {//拆零数量
//							addParam.setOpenStockSkuKindNum(Long.valueOf(open_stock_sku_kind_num));
//						}

						String order_type = jsonObject2.get("order_type").toString();
						if (ToolUtil.isNotEmpty(order_type)) {//单据类型
							addParam.setOrderType(order_type);
						}

//						String quantity = jsonObject2.get("quantity").toString();
//						if (ToolUtil.isNotEmpty(quantity)) {//申请数量
//							addParam.setQuantity(Long.valueOf(quantity));
//						}

						String state = jsonObject2.get("state").toString();
						if (ToolUtil.isNotEmpty(state)) {//状态
							addParam.setState(state);
						}

						String store_id = jsonObject2.get("store_id").toString();
						if (ToolUtil.isNotEmpty(store_id)) {//发货门店id
							addParam.setStoreId(store_id);
						}

						String store_name = jsonObject2.get("store_name").toString();
						if (ToolUtil.isNotEmpty(store_name)&&!store_name.equals("null")) {//发货门店名称
							addParam.setStoreName(store_name);
						} else {
							if(c.getStoreIdXlb().equals("6666600000629")) {
								addParam.setStoreName("山东德州仓");
							}
							if(c.getStoreIdXlb().equals("6866800000001")) {
								addParam.setStoreName("辽宁沈阳仓");
							}
							if(c.getStoreIdXlb().equals("6666600000628")) {
								addParam.setStoreName("山东潍坊仓");
							}
							if(c.getStoreIdXlb().equals("6666600000312")) {
								addParam.setStoreName("安徽亳州仓");
							}
							if(c.getStoreIdXlb().equals("6666600001990")) {
								addParam.setStoreName("天津仓");
							}
						}

						String storehouse_id = jsonObject2.get("storehouse_id").toString();
						if (ToolUtil.isNotEmpty(storehouse_id)) {//发货仓库id
							addParam.setStorehouseId(storehouse_id);
						}

						String storehouse_name = jsonObject2.get("storehouse_name").toString();
						if (ToolUtil.isNotEmpty(storehouse_name)&&!storehouse_name.equals("null")) {//发货仓库名称
							addParam.setStorehouseName(storehouse_name);
						} else {
							if(c.getStoreIdXlb().equals("6666600000629")) {
								addParam.setStorehouseName("山东德州仓仓库");
							}
							if(c.getStoreIdXlb().equals("6866800000001")) {
								addParam.setStorehouseName("辽宁沈阳仓仓库");
							}
							if(c.getStoreIdXlb().equals("6666600000628")) {
								addParam.setStorehouseName("山东潍坊仓仓库");
							}
							if(c.getStoreIdXlb().equals("6666600000312")) {
								addParam.setStorehouseName("安徽亳州仓仓库");
							}
							if(c.getStoreIdXlb().equals("6666600001990")) {
								addParam.setStorehouseName("天津仓仓库");
							}
						}

						String volume = jsonObject2.get("volume").toString();
						if (ToolUtil.isNotEmpty(volume)) {//体积
							addParam.setVolume(new BigDecimal(volume).setScale(4, BigDecimal.ROUND_HALF_DOWN));
						}

//						String whole_quantity = jsonObject2.get("whole_quantity").toString();
//						if (ToolUtil.isNotEmpty(whole_quantity)) {//整件数量
//							addParam.setWholeQuantity(Long.valueOf(whole_quantity));
//						}

//						String whole_sku_kind_num = jsonObject2.get("whole_sku_kind_num").toString();
//						if (ToolUtil.isNotEmpty(whole_sku_kind_num)&&!whole_sku_kind_num.equals("null")) {//整件sku数
//							addParam.setWholeSkuKindNum(Long.valueOf(whole_sku_kind_num));
//						}

						addParam.setCreateTime(new Date());
						addParam.setCreateUser(user.getUserId());
						addParam.setDeptId(c.getDeptId());
						addParam.setDeliverId(c.getDeliverId());
						addParam.setDataDt(ModifiedDate);
						addParam.setCustomerId(customerId);
						add.add(addParam);
					}
					if(add.size()>0) {
						OrderClientVolDetailParam delParam = new OrderClientVolDetailParam();
						delParam.setCustomerId(customerId);
						delParam.setDataDt(ModifiedDate);
						orderClientVolDetailService.deleteBySpec(delParam); // TODO 方法空了！！！！！！！！
						orderClientVolDetailService.saveBatch(add);
						//同步到门店汇总信息表
						OrderClientVolSumParam param = new OrderClientVolSumParam();
						param.setCustomerId(customerId);
						param.setDataDt(ModifiedDate);
						orderClientVolSumService.deleteByDateDt(param);
						//获取地址信息
						Map<String,BasicAddressResult> addressMap = new HashMap<>();
						BasicAddressParam addressParam = new BasicAddressParam();
//						addressParam.setDeliverId(c.getDeliverId());
//						addressParam.setDeptId(c.getDeptId());
						List<BasicAddressResult> addressLists = basicAddressService.findListBySpec(addressParam);
						for(BasicAddressResult obj : addressLists){
							addressMap.put(obj.getPutgoodsName(),obj);
						}
						//甩托
						Map<String,OrderClientVolSumResult> shuaiTuoMap = new HashMap<>();
						param = new OrderClientVolSumParam();
						param.setDeptId(c.getDeptId());
						List<OrderClientVolSumResult> clientSumList = orderClientVolSumService.getShuaiTuoList(param,user.getOperateId());
						for(OrderClientVolSumResult obj : clientSumList){
							shuaiTuoMap.put(obj.getClientId(),obj);
						}
						//获取本次的新增数据
						param = new OrderClientVolSumParam();
						param.setCustomerId(customerId);
						param.setDataDt(ModifiedDate);
						clientSumList = orderClientVolSumService.getClientSumList(param);
						List<OrderClientVolSum> addOrderClientVolSumList = new ArrayList<>();
						OrderClientVolSum addOrderClientVolSum = null;
						for(OrderClientVolSumResult obj : clientSumList){
							BigDecimal volume = obj.getVolume();
							if(shuaiTuoMap.get(obj.getClientId()) != null){
								volume = volume.add(shuaiTuoMap.get(obj.getClientId()).getVolume());
							}
							addOrderClientVolSum = new OrderClientVolSum();
							addOrderClientVolSum.setClientId(obj.getClientId());
							addOrderClientVolSum.setClientName(obj.getClientName());
							addOrderClientVolSum.setCustomerId(customerId);
							addOrderClientVolSum.setDataDt(obj.getDataDt());
							addOrderClientVolSum.setStorehouseId(obj.getStorehouseId());
							addOrderClientVolSum.setStorehouseName(obj.getStorehouseName());
							addOrderClientVolSum.setVolume(volume);
							addOrderClientVolSum.setUndisVolume(volume);
							if(addressMap.get(obj.getClientName()) != null){
								addOrderClientVolSum.setSheng(addressMap.get(obj.getClientName()).getSheng());
								addOrderClientVolSum.setShi(addressMap.get(obj.getClientName()).getShi());
								addOrderClientVolSum.setQu(addressMap.get(obj.getClientName()).getQu());
							}
							addOrderClientVolSum.setDeliverId(c.getDeliverId());
							addOrderClientVolSum.setDeptId(c.getDeptId());
							addOrderClientVolSum.setCreateUser(user.getUserId());
							addOrderClientVolSum.setCreateTime(new Date());
							addOrderClientVolSumList.add(addOrderClientVolSum);
						}
						if(addOrderClientVolSumList.size() > 0){
							orderClientVolSumService.saveBatch(addOrderClientVolSumList,5000);
						}

					}
				}
			}
		}
		return ResponseData.success();
	}

    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/orderOutcountXlb_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/orderOutcountXlb_edit.html";
    }


	@RequestMapping("/toctj")
	public String toctj() {
		return PREFIX + "/orderOutcountXlb_ctj.html";
	}

    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(OrderOutcountXlbParam orderOutcountXlbParam) {
        this.orderOutcountXlbService.add(orderOutcountXlbParam);
        return ResponseData.success();
    }


	@RequestMapping("/ctj")
	@ResponseBody
	public ResponseData ctj(OrderClientVolSumParam param) {
		if (param.getCVolume().compareTo(param.getUndisVolume()) == 1) {
			return ResponseData.error("拆出的体积不能大于剩余体积");
		}
    	this.orderClientVolSumService.ctj(param);
		return ResponseData.success();
	}

    /**
     * 编辑接口
     *
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(OrderOutcountXlbParam orderOutcountXlbParam) {
        this.orderOutcountXlbService.update(orderOutcountXlbParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(OrderOutcountXlbParam orderOutcountXlbParam) {
        this.orderOutcountXlbService.delete(orderOutcountXlbParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-09-30
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(OrderOutcountXlbParam orderOutcountXlbParam) {
        OrderOutcountXlb detail = this.orderOutcountXlbService.getById(orderOutcountXlbParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-09-30
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(OrderOutcountXlbParam orderOutcountXlbParam,String condition ,String startTime,String endTime) {
    	User user = userService.getcurrentUser();
    	orderOutcountXlbParam.setDeptId(user.getDeptId());
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		orderOutcountXlbParam.setV1("'"+startTime+"' and '"+endTime+"'");
		} else if (startTime == null && endTime == null){
			orderOutcountXlbParam.setV1("'"+DateUtil.getDate()+"' and '"+ DateUtil.getDate()+"'");
		}
//		orderOutcountXlbParam.setIsRePrepare("YES");
        return this.orderOutcountXlbService.findPageBySpec(orderOutcountXlbParam,condition,user.getOperateId());
    }


	/**
	 * 查询列表
	 *
	 * @author zhucx
	 * @Date 2023-09-30
	 */
	@ResponseBody
	@RequestMapping("/listNew")
	public LayuiPageInfo listNew(OrderClientVolSumParam param) {
		User user = userService.getcurrentUser();
		param.setDeptId(user.getDeptId());

		// 1.承运商角色隔离
		String roleId = user.getRoleId();
		if(ToolUtil.isNotEmpty(roleId)){
			for(String rId : roleId.split(",")){
				Role byId = roleService.getById(rId);
				if(byId != null && byId.getName().contains("承运商")){
					BasicCarrierParam paramC = new BasicCarrierParam();
					paramC.setUserId(user.getUserId());
					BasicCarrierResult bySpec = basicCarrierService.findBySpec(paramC, user.getOperateId());
					if(bySpec != null){
						param.setCarrierId(bySpec.getId());
					}else{
						param.setCarrierId(-1);
					}
				}
			}
		}

		// 2.默认当天数据
		if(ToolUtil.isEmpty(param.getDataDt())){
			param.setDataDt(DateUtil.getDate());
		}

		return this.orderClientVolSumService.findPageBySpec(param);
	}

}


